package com.milepost.workflow.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.milepost.workflow.user.entity.UsersEntity;
import com.milepost.workflow.user.mapper.UserMapper;
import com.milepost.workflow.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author huarf
 * @Description
 * @create 2022-03-23 22:31
 */
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, UsersEntity> implements UserService {

    private final UserMapper userMapper;

    @Override
    public void testTx() {
        UsersEntity userEntity = new UsersEntity();
        userEntity.setId("1");
        userEntity.setName("张三2");
        int i1 = baseMapper.updateById(userEntity);
        System.out.println(i1);

        //int i = 1/0;

        userEntity.setName("张三3");
        int i2 = baseMapper.updateById(userEntity);
        System.out.println(i2);
    }

    @Override
    public void testPage() {

        Page<UsersEntity> page = new Page<>(1, 4);
        Page<UsersEntity> result = baseMapper.selectPage(page, Wrappers.<UsersEntity>lambdaQuery().like(UsersEntity::getName, "1").orderByAsc(UsersEntity::getIdNum));
        System.out.println(result.getTotal());
        System.out.println(result.getRecords().size());
        for (UsersEntity userEntity : result.getRecords()) {
            System.out.println(userEntity);
        }
    }

    @Override
    public List<UsersEntity> testCustomSql(String name) {
        return userMapper.getByName("%"+ name +"%");
    }

    @Override
    public String getUserNamesByIds(String assignees) {

        StringBuilder stringBuilder = new StringBuilder("");
        List<UsersEntity> userEntities = userMapper.selectList(new QueryWrapper<UsersEntity>().lambda()
                .in(UsersEntity::getId, assignees.split(",")));

        for (UsersEntity userEntity : userEntities) {
            stringBuilder.append(userEntity.getName()).append(",");
        }

        stringBuilder.deleteCharAt(stringBuilder.length()-1);
        return stringBuilder.toString();
    }

    @Override
    public UsersEntity getByUserName(String userName) {

        UsersEntity userEntity = baseMapper.selectOne(Wrappers.<UsersEntity>lambdaQuery()
                .eq(UsersEntity::getCode, userName)
        );

        if (userEntity == null) {
            throw new RuntimeException("未查询到用户数据");
        }

        return userEntity;
    }

}
